#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mpi.h"

int
main(int argc, char **argv)
{
	int size, rank, i;
	int success = 1;
	
	int sendbuf[2] = {4,8};
	int *recvbuf = NULL;

	setbuf(stdout,NULL);
	printf("before init\n");
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	printf("Size %d, Rank %d\n",size,rank);
	
	if( rank == 0 )
	{
		recvbuf = (int *)malloc(size*2*sizeof(int)); 
		MPI_Gather(sendbuf,2,MPI_INT,recvbuf, 2, MPI_INT, 0, MPI_COMM_WORLD);
		printf("GATHER: recvbuf[0]: %d recvbuf[1]: %d\n",
				recvbuf[0], recvbuf[1]);
		success = success && (recvbuf[0] == 4);
		success = success && (recvbuf[1] == 8);
		for (i = 2; i < size*2; i++) {
			if (i % 2 == 0) {
				printf("GATHER: recvbuf[%d]: %d recvbuf[%d]: %d\n",
					i, recvbuf[i], i+1, recvbuf[i+1]);
				success = success && (recvbuf[i] == 1);
			} else {
				success = success && (recvbuf[i] == 2);
			}
		}

		if (success == 1) {
			printf("SUCCESS\n");
		}
		else
		{
			printf("FAILURE\n");
		}

	}
	else 
	{
		sendbuf[0] = 1;
		sendbuf[1] = 2;
		MPI_Gather(sendbuf,2,MPI_INT,recvbuf, 2, MPI_INT, 0, MPI_COMM_WORLD);
		printf("GATHER: sendbuf[0]: %d sendbuf[1]: %d\n", sendbuf[0], sendbuf[1]);
	}
	
	
	MPI_Finalize();
	return 0;
}

